//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.vere.rpc.util;

import com.vere.rpc.server.CacheData;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class ObjectUtil {
    public ObjectUtil() {
    }

    public static void sendObject(SocketChannel socketChannel, Object obj) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(obj);
        oos.flush();
        oos.close();
        byte[] bytes = baos.toByteArray();
        ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
        buffer.put(bytes);
        buffer.flip();
        socketChannel.write(buffer);
        buffer.clear();
    }

    public static Object receiveObject(SocketChannel socketChannel) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        boolean var3 = false;

        int len;
        while((len = socketChannel.read(buffer)) > 0) {
            buffer.flip();
            baos.write(buffer.array());
            buffer.clear();
        }

        if (baos.size() > 0 && len != -1) {
            byte[] bytes = baos.toByteArray();
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(bais);

            try {
                Object var9 = ois.readObject();
                return var9;
            } catch (ClassNotFoundException var12) {
                var12.printStackTrace();
            } finally {
                ois.close();
            }

            return null;
        } else {
            close(socketChannel);
            return null;
        }
    }

    public static void close(SocketChannel socketChannel) {
        String clientId = socketChannel.socket().getRemoteSocketAddress().toString();
        CacheData.remove(clientId);

        try {
            socketChannel.close();
        } catch (IOException var3) {
            var3.printStackTrace();
        }

    }
}
